import 'dart:convert';
import 'dart:typed_data';
import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_ncsjqz_getx/http/dio_service.dart';
import 'package:flutter_ncsjqz_getx/model/user_detail_entity.dart';
import 'package:flutter_ncsjqz_getx/util/toast_util.dart';
import 'package:flutter_ncsjqz_getx/widget/app_bar_widget.dart';
import 'package:flutter_ncsjqz_getx/widget/ink_widget.dart';
import 'package:get/get.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:qr_flutter/qr_flutter.dart';

/// <summary>
/// author：zwb
/// dateTime： 2022/1/17 14:51
/// filePath： lib/page/rong_im/conversation_list/my_code_page.dart
/// desc: 我的加好友二维码
/// <summary>
///
class MyCodePage extends StatefulWidget {
  const MyCodePage({Key? key,}) : super(key: key);

  @override
  _MyCodePageState createState() => _MyCodePageState();
}

class _MyCodePageState extends State<MyCodePage> {
  String codeStr = '我的';
  GlobalKey globalKey = GlobalKey();
  UserDetailData? data;

  getUser() async{
    // 获取用户信息
    UserDetailEntity data = await DioService<UserDetailEntity>().queryPersonalDetail();
    setState(() {
      if(data.code == 0) {
        this.data = data.data;
        codeStr = json.encode({
          "type":1,
          "userId": data.data!.id!,
          "ryUserId":data.data!.ryUserId,
        });
      }
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getUser();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey.shade100,
      appBar:  appBarWidget(title: "我的二维码名片"),
      body: data == null ? SizedBox():Container(
        child:  Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            RepaintBoundary(
              key: globalKey,
              child: Container(
                width: Get.width,
                color: Colors.white,
                padding: EdgeInsets.all(15),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Container(
                      width: Get.width,
                      child: Row(
                        children: [
                          InkWidget.imgNet("${data!.userPic ?? ''}",width: 50,height: 50,borderRadius: BorderRadius.circular(5),),
                          InkWidget.text("  ${data!.nickName ?? ''}"),
                        ],
                      ),
                    ),
                    Container(
                      width:Get.width / 1.8,
                      height:Get.width / 1.8,
                      margin: EdgeInsets.symmetric(vertical: 30),
                      decoration: BoxDecoration(
                          color: Colors.white,
                          border: Border.all(color: Colors.grey.shade200)
                      ),
                      child: Stack(
                        children: [
                          QrImage(
                            data: "$codeStr",
                            version: QrVersions.auto,
                            size: Get.width / 1.8,
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),

            SizedBox(
              height: 20,
            ),
            Row(
              children: [
                Expanded(
                  child: OutlineButton(
                    shape: StadiumBorder(),
                    borderSide: BorderSide(color: Colors.green,),
                    child: InkWidget.text("保存图片",color: Colors.green),
                    onPressed: ()  async{
                      saveImg();
                    },
                  ),
                ),
              ],
            ),
          ],
        ),
        width: Get.width,
        padding: EdgeInsets.all(15),
      ),
    );
  }

  /// 保存图片
  Future<String> saveImg() async{
    String path = "";
    //检查是否有存储权限
    if (!await Permission.storage.request().isGranted){
      toast("没有存储权限，二维码保存失败");
    }else{
      //截图
      RenderRepaintBoundary boundary = globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
      ui.Image image = await boundary.toImage();
      ByteData? byteData = await (image.toByteData(format: ui.ImageByteFormat.png));
      // 保存
      if (byteData != null) {
        final result = await ImageGallerySaver.saveImage(byteData.buffer.asUint8List(), );
        if(result["isSuccess"]){
          path = result["filePath"];
          toast("保存成功");
        }else{
          toast("保存失败");
        }
      }
    }
    return path;
  }
}
